package net.a6polo.renren.ui;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.LinkedList;
import java.util.List;

import net.a6polo.a6poloweibo.IndexActivity;
import net.a6polo.a6poloweibo.R;
import net.a6polo.a6poloweibo.RenrenIndexActivity;
import net.a6polo.a6poloweibo.Writeweiboactivity;
import net.a6polo.a6poloweibo.util.A6poloUtil;
import net.a6polo.a6poloweibo.view.DropDownToRefreshListView;
import net.a6polo.a6poloweibo.view.DropDownToRefreshListView.OnRefreshListener;
import net.a6polo.a6poloweibo.view.MyProgressDialog;
import net.a6polo.renren.RenrenAPIV2;
import net.a6polo.renren.domain.AccessToken;
import net.a6polo.renren.domain.ErrorCode;
import net.a6polo.renren.domain.ErrorRequest;
import net.a6polo.renren.domain.FeedResponse;
import net.a6polo.renren.net.RequestListener;
import net.a6polo.renren.ui.adapter.RenrenTimelineListViewAdapter;
import net.a6polo.renren.domain.UserInfo;
import net.a6polo.service.Service;
import net.a6polo.service.SnsType;
import net.a6polo.service.domain.Account;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class RenrenFeedActivity extends Activity implements OnClickListener {

	private Handler handler = null;

	private List<FeedResponse> timeline = null;

	private DropDownToRefreshListView timeLineListView = null;
	
	private RenrenTimelineListViewAdapter renrenTimelineListViewAdapter;

	private Exception exception;
	
	private int pageNo = 1;
	
	private int pageSize = 20;
	
	private long maxId = 0;
	
	private Dialog progressDialog;
	
	private RenrenAPIV2 renrenAPI;
	
	private UserInfo userInfo;
	
	private TextView title;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		renrenAPI = new RenrenAPIV2(RenrenFeedActivity.this);
		
		progressDialog = new MyProgressDialog(this, R.style.CustomProgressDialog); 

		handler = new Handler();
		timeLineListView = (DropDownToRefreshListView) findViewById(R.id.timeLineListView);
		Button timelineButton = (Button) findViewById(R.id.btn_refresh);
		timelineButton.setOnClickListener(this);

		Button writeButton = (Button) findViewById(R.id.btn_writer);
		writeButton.setOnClickListener(this);

		Service service = new Service(RenrenFeedActivity.this);
		Account renrenAccount = service.getLastAccountByType(SnsType.RENREN);
		title = (TextView) findViewById(R.id.txt_wb_title);
		title.setText(renrenAccount.getUserName());

		timeLineListView.setOnRefreshListener(new OnRefreshListener() {
			@Override
			public void onRefresh() {
				timelineButtonListener();
				timeLineListView.onRefreshComplete("松开可刷新");
			}

		});

		timeLineListView.setOnLoadMoreListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				more();
			}

		});
		
		
		//renrenAPI.getUserInfo(new GetUserInfoRequestListener());
		
		
		

		if (null == timeline || timeline.size() == 0) {
			progressDialog.show();
			timelineButtonListener();
			// refresh();
		}

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_refresh: {
			timelineButtonListener();
			break;
		}
		case R.id.btn_writer: {
			Intent intent = new Intent();
			intent.setClass(RenrenFeedActivity.this, Writeweiboactivity.class);
			startActivity(intent);

			break;
		}
		default:
			break;
		}

	}

	public void timelineButtonListener() {
				
		progressDialog.show();
		
		new Thread() {
			public void run() {
				renrenAPI.getFeed(1, 20, new MyRequestListener());
			}
		}.start();

	}

	class MyRequestListener implements RequestListener {

		@Override
		public void onComplete(String arg0) {
			Gson gson = new Gson();
			Log.d("a6polo", "result:" + arg0);	
			try{
				
				Type listType = new TypeToken<LinkedList<FeedResponse>>(){}.getType();
				timeline = gson.fromJson(arg0, listType);
				Log.d("a6polo", "result size:" + timeline.size());
				handler.post(runnableUi);
				int maxIndex = timeline.size();
				if(maxIndex > 0) {
					maxIndex = maxIndex -1;
				}
				maxId = timeline.get(maxIndex).getPost_id();
				progressDialog.dismiss();
			} catch (JsonSyntaxException e) {
				ErrorRequest errorRequest = gson.fromJson(arg0, ErrorRequest.class);
				if(ErrorCode.EXPIRED_ACCESS_TOKEN == errorRequest.getError_code()) {
					renrenAPI = new RenrenAPIV2(RenrenFeedActivity.this);
					renrenAPI.refreshToken(new RefreshTokenRequestListener());
				}
				
			}		
		}

		@Override
		public void onError(Exception e) {
			exception = e;
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					Toast.makeText(getApplicationContext(), " error : " + exception.getMessage(), Toast.LENGTH_LONG)
							.show();
				}
			});

		}

		@Override
		public void onIOException(IOException e) {
			exception = e;
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					Toast.makeText(getApplicationContext(), " error : " + exception.getMessage(), Toast.LENGTH_LONG)
							.show();
				}
			});
		}

	}
	
	Runnable runnableUi = new Runnable() {
		@Override
		public void run() {
			loadDate(timeline);
			//timeLineListView.onRefreshComplete("更新完成");
		}
	};
	
	class MyMoreRequestListener implements RequestListener {

		@Override
		public void onComplete(String arg0) {
			Gson gson = new Gson();
			Log.d("a6polo", "result:" + arg0);
			
			try{
				Type listType = new TypeToken<LinkedList<FeedResponse>>(){}.getType();
				timeline = gson.fromJson(arg0, listType);
				Log.d("a6polo", "result size:" + timeline.size());
				handler.post(runnableMoreUi);
				progressDialog.dismiss();
			}catch (JsonSyntaxException e) {
				ErrorRequest errorRequest = gson.fromJson(arg0, ErrorRequest.class);
				if(ErrorCode.EXPIRED_ACCESS_TOKEN == errorRequest.getError_code()) {
					renrenAPI = new RenrenAPIV2(RenrenFeedActivity.this);
					renrenAPI.refreshToken(new RefreshTokenRequestListener());
				}
				
			}	
		}

		@Override
		public void onError(Exception e) {
			exception = e;
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					Toast.makeText(getApplicationContext(), " error : " + exception.getMessage(), Toast.LENGTH_LONG)
							.show();
				}
			});

		}

		@Override
		public void onIOException(IOException e) {
			exception = e;
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					Toast.makeText(getApplicationContext(), " error : " + exception.getMessage(), Toast.LENGTH_LONG)
							.show();
				}
			});
		}

	}
	
	Runnable runnableMoreUi = new Runnable() {
		@Override
		public void run() {
			addData(timeline);
			
		}
	};

	public void loadDate(List<FeedResponse> timeline) {
		renrenTimelineListViewAdapter = new RenrenTimelineListViewAdapter(timeline, this);
		timeLineListView.setAdapter(renrenTimelineListViewAdapter);

	}
	
	public void addData(List<FeedResponse> timeline) {
		renrenTimelineListViewAdapter.addItem(timeline);		
		renrenTimelineListViewAdapter.notifyDataSetChanged();


	}

	public void more() {
		pageNo++;
		new Thread() {
			public void run() {
				renrenAPI.getFeed(pageNo, 20, new MyMoreRequestListener());
			}
		}.start();

	}
	
//	class GetUserInfoRequestListener implements RequestListener {
//
//		@Override
//		public void onComplete(String response) {
//			Gson gson = new Gson();
//			Log.d("a6polo", "result:" + response);
//			
//			Type listType = new TypeToken<LinkedList<UserInfo>>(){}.getType();
//			
//			try{
//				List<UserInfo> userInfoList = gson.fromJson(response, listType);
//				userInfo = userInfoList.get(0);
//				handler.post(userInfoUi);
//			} catch (JsonSyntaxException e) {
//				ErrorRequest errorRequest = gson.fromJson(response, ErrorRequest.class);
//				if(ErrorCode.EXPIRED_ACCESS_TOKEN == errorRequest.getError_code()) {
//				
//					renrenAPI = new RenrenAPIV2(RenrenFeedActivity.this);
//					renrenAPI.refreshToken(new RefreshTokenRequestListener());
//				}
//				
//			}			
//		}
//
//		@Override
//		public void onIOException(IOException e) {
//			exception = e;
//			runOnUiThread(new Runnable() {
//				@Override
//				public void run() {
//					Toast.makeText(getApplicationContext(), " error : " + exception.getMessage(), Toast.LENGTH_LONG)
//							.show();
//				}
//			});
//		}
//
//		@Override
//		public void onError(Exception e) {
//			exception = e;
//			runOnUiThread(new Runnable() {
//				@Override
//				public void run() {
//					Toast.makeText(getApplicationContext(), " error : " + exception.getMessage(), Toast.LENGTH_LONG)
//							.show();
//				}
//			});
//		}
//		
//	}
//	
//	Runnable userInfoUi = new Runnable() {
//		@Override
//		public void run() {
//			title.setText(userInfo.getName());
//			
//		}
//	};

	
	class RefreshTokenRequestListener implements RequestListener {

		@Override
		public void onComplete(String response) {
			Gson gson = new Gson();
			Log.d("a6polo", "result:" + response);
			AccessToken accessToken = gson.fromJson(response, AccessToken.class);
			
			Service service = new Service(RenrenFeedActivity.this);
			Account renrenAccount = service.getLastAccountByType(SnsType.RENREN);
			renrenAccount.setAccessToken(accessToken.getAccess_token());
			renrenAccount.setRefreshToken(accessToken.getRefresh_token());
			service.update(renrenAccount);
			
//			A6poloUtil.saveToPreferences(RenrenFeedActivity.this, "renren_token", "accessToken", accessToken.getAccess_token());
//            A6poloUtil.saveToPreferences(RenrenFeedActivity.this, "renren_token", "refresh_token", accessToken.getRefresh_token());
		}

		@Override
		public void onIOException(IOException e) {
			exception = e;
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					Toast.makeText(getApplicationContext(), " error : " + exception.getMessage(), Toast.LENGTH_LONG)
							.show();
				}
			});
		}

		@Override
		public void onError(Exception e) {
			exception = e;
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					Toast.makeText(getApplicationContext(), " error : " + exception.getMessage(), Toast.LENGTH_LONG)
							.show();
				}
			});
		}
		
	}
}
